from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView

from bigevents_admin.authenticate import JWTAuth
from category.models import Category
from bigevents_admin.serializers.cates import CategorySerializer


class GetCatesView(APIView):
    """获取文章分类列表"""
    authentication_classes = (JWTAuth,)

    def get(self, request):
        cates = Category.objects.filter(is_delete=0)
        serializer = CategorySerializer(cates, many=True)
        data = serializer.data
        return Response({'status': 0, 'message': '获取文章分类列表成功！', 'data': data})


class AddCatesView(GenericAPIView):
    """新增文章分类"""
    authentication_classes = (JWTAuth,)

    queryset = Category.objects.all()
    serializer_class = CategorySerializer

    def post(self, request):
        serializer = self.get_serializer(data=request.data)
        try:
            serializer.is_valid(raise_exception=True)
            serializer.save()
            return Response({'status': 0, 'message': '新增文章分类成功！'})
        except Exception as e:
            return Response({'status': 1, 'message': '新增文章分类失败！'})


class DeleteCateView(APIView):
    """根据 Id 删除文章分类"""
    authentication_classes = (JWTAuth,)

    def get(self, request, id):
        try:
            cate = Category.objects.get(id=id)
        except Exception as e:
            return Response({'status': 1, 'message': '删除文章分类失败！'})

        if cate.name not in ['科技', '最新']:
            cate.is_delete = 1
            cate.save()
            return Response({'status': 0, 'message': '删除文章分类成功！'})
        else:
            return Response({'status': 1, 'message': '删除文章分类失败！'})


class GetCateView(APIView):
    """根据 Id 获取文章分类数据"""
    authentication_classes = (JWTAuth,)

    def get(self, request, id):
        try:
            cate = Category.objects.get(id=id)
        except Exception as e:
            return Response({'status': 1, 'message': '获取文章分类数据失败！'})
        serializer = CategorySerializer(cate)
        return Response({'status': 0, 'message': '获取文章分类数据成功！', 'data': serializer.data})


class UpdateCateView(APIView):
    """根据 Id 更新文章分类数据"""
    authentication_classes = (JWTAuth,)

    def post(self, request):
        # 获取选中的分类id
        id = request.data.get('id')
        # 获取对应的分类实例
        cate = Category.objects.get(id=int(id))
        serializer = CategorySerializer(data=request.data)
        try:
            serializer.is_valid(raise_exception=True)
        except Exception as e:
            return Response({'status': 1, 'message': '更新分类信息失败！'})
        data = serializer.data
        # 更新数据
        cate.name = data['name']
        cate.alias = data['alias']
        cate.save()
        return Response({'status': 0, 'message': '更新分类信息成功！'})
